package com.university.mentalhealthplatform.global.log.login;

import com.university.mentalhealthplatform.global.log.dto.IdRequest;
import com.university.mentalhealthplatform.global.log.dto.LoginLogDTO;
import com.university.mentalhealthplatform.utils.PagedResponse;
import com.university.mentalhealthplatform.utils.stringUtils.ConvertEmptyToNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/login-logs")
public class LoginLogController {

    @Autowired
    private LoginLogService loginLogService;

    @GetMapping
    public ResponseEntity<PagedResponse<LoginLogDTO>> getLoginLogs(
            @RequestParam(required = false) @ConvertEmptyToNull String loginName,
            @RequestParam(required = false) @ConvertEmptyToNull String loginAddress,
            @RequestParam(required = false) @ConvertEmptyToNull String loginStatus,
            @RequestParam(required = false) @ConvertEmptyToNull String loginLocation,
            @RequestParam(required = false) @ConvertEmptyToNull String browser,
            @RequestParam(required = false) @ConvertEmptyToNull String operatingSystem,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
            @RequestParam(defaultValue = "1") int page,        // 默认页码为1
            @RequestParam(defaultValue = "10") int pageSize,   // 默认每页大小为10
            @RequestParam(required = false) String sortField,  // 排序字段
            @RequestParam(required = false) String sortOrder) { // 排序顺序

        // 调用 Service 层获取分页数据
        PagedResponse<LoginLogDTO> result = loginLogService.getLoginLogs(
                loginName, loginStatus, loginAddress, loginLocation, browser, operatingSystem,
                startDate, endDate, page - 1, pageSize, sortField, sortOrder);

        return ResponseEntity.ok(result);
    }




    @PostMapping("/delete")
    public ResponseEntity<Void> deleteLoginLogsByIds(@RequestBody IdRequest request) {
        loginLogService.deleteLoginLogsByIds(request.getIds().toArray(new Long[0]));
        return ResponseEntity.noContent().build();
    }


    @PostMapping("/clear")
    public ResponseEntity<Void> clearAllLoginLogs() {
        loginLogService.clearAllLoginLogs();
        return ResponseEntity.noContent().build();
    }
}
